package com.bw.common.utils

import android.app.Activity
import android.os.Build
import android.view.View
import android.view.WindowManager
import androidx.appcompat.app.AppCompatDelegate
import android.content.Context
import android.content.SharedPreferences
import android.os.Handler
import android.os.Looper

object ImmersiveNightModeUtil {
    
    private const val PREF_NAME = "night_mode_pref"
    private const val KEY_NIGHT_MODE = "night_mode_enabled"
    private var isTransitioning = false // 防止重复切换

    /**
     * 设置沉浸式状态栏
     */
    fun setImmersiveStatusBar(activity: Activity, darkIcons: Boolean = true) {
        val window = activity.window
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = android.graphics.Color.TRANSPARENT
            val decor = window.decorView
            var vis = decor.systemUiVisibility
            vis = vis or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            if (darkIcons && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                vis = vis or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            }
            decor.systemUiVisibility = vis
        }
    }

    /**
     * 平滑切换夜间模式（防闪屏）
     * @param enableNight true为夜间模式，false为日间模式
     */
    fun setNightMode(enableNight: Boolean) {
        if (isTransitioning) return // 防止重复切换
        
        isTransitioning = true
        
        // 保存设置到SharedPreferences
        val context = getApplicationContext()
        if (context != null) {
            val prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
            prefs.edit().putBoolean(KEY_NIGHT_MODE, enableNight).apply()
        }
        
        // 延迟切换，给UI一些时间准备
        Handler(Looper.getMainLooper()).postDelayed({
            try {
                // 设置主题模式
                AppCompatDelegate.setDefaultNightMode(
                    if (enableNight) AppCompatDelegate.MODE_NIGHT_YES else AppCompatDelegate.MODE_NIGHT_NO
                )
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                // 延迟重置状态，防止快速重复切换
                Handler(Looper.getMainLooper()).postDelayed({
                    isTransitioning = false
                }, 500)
            }
        }, 100)
    }

    /**
     * 跟随系统切换夜间模式
     */
    fun followSystemNightMode() {
        if (isTransitioning) return
        
        isTransitioning = true
        
        val context = getApplicationContext()
        if (context != null) {
            val prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
            prefs.edit().remove(KEY_NIGHT_MODE).apply()
        }
        
        Handler(Looper.getMainLooper()).postDelayed({
            try {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                Handler(Looper.getMainLooper()).postDelayed({
                    isTransitioning = false
                }, 500)
            }
        }, 100)
    }
    
    /**
     * 获取当前夜间模式状态
     */
    fun isNightModeEnabled(): Boolean {
        val context = getApplicationContext()
        return context?.let {
            val prefs = it.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
            prefs.getBoolean(KEY_NIGHT_MODE, false)
        } ?: false
    }
    
    /**
     * 应用保存的夜间模式设置
     */
    fun applySavedNightMode() {
        val context = getApplicationContext()
        if (context != null) {
            val prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
            if (prefs.contains(KEY_NIGHT_MODE)) {
                val isNightMode = prefs.getBoolean(KEY_NIGHT_MODE, false)
                AppCompatDelegate.setDefaultNightMode(
                    if (isNightMode) AppCompatDelegate.MODE_NIGHT_YES else AppCompatDelegate.MODE_NIGHT_NO
                )
            }
        }
    }

    /**
     * 设置沉浸式状态栏并在下拉后5秒自动恢复
     */
    fun setImmersiveStatusBarWithAutoHide(activity: Activity, darkIcons: Boolean = true, autoHideDelay: Long = 5000L) {
        setImmersiveStatusBar(activity, darkIcons)
        val decorView = activity.window.decorView
        decorView.setOnSystemUiVisibilityChangeListener { visibility ->
            // 如果状态栏被拉下（非沉浸式）
            if (visibility and View.SYSTEM_UI_FLAG_FULLSCREEN == 0) {
                decorView.postDelayed({
                    setImmersiveStatusBar(activity, darkIcons)
                }, autoHideDelay)
            }
        }
    }

    /**
     * 设置游戏式沉浸式状态栏（默认隐藏，下拉显示，几秒后自动隐藏）
     */
    fun setGameImmersiveStatusBar(activity: Activity, autoHideDelay: Long = 3000L) {
        val window = activity.window
        val decorView = window.decorView
        
        // 设置全屏隐藏状态栏
        val flags = (View.SYSTEM_UI_FLAG_FULLSCREEN
                or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
        
        decorView.systemUiVisibility = flags
        
        // 监听系统UI可见性变化
        decorView.setOnSystemUiVisibilityChangeListener { visibility ->
            // 如果状态栏被拉下显示（非全屏）
            if (visibility and View.SYSTEM_UI_FLAG_FULLSCREEN == 0) {
                // 延迟几秒后重新隐藏
                decorView.postDelayed({
                    decorView.systemUiVisibility = flags
                }, autoHideDelay)
            }
        }
    }
    
    /**
     * 获取Application Context
     */
    private fun getApplicationContext(): Context? {
        return try {
            // 尝试通过反射获取Application Context
            val activityThreadClass = Class.forName("android.app.ActivityThread")
            val currentActivityThreadMethod = activityThreadClass.getDeclaredMethod("currentActivityThread")
            val currentActivityThread = currentActivityThreadMethod.invoke(null)
            val getApplicationMethod = activityThreadClass.getDeclaredMethod("getApplication")
            getApplicationMethod.invoke(currentActivityThread) as Context
        } catch (e: Exception) {
            null
        }
    }
}
